﻿using Microsoft.AspNetCore.JsonPatch.Operations;
using Microsoft.AspNetCore.Mvc.Authorization;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Swashbuckle.AspNetCore.SwaggerGen
{
  public class AuthorizationHeaderParameterOperationFilter : IOperationFilter, IDocumentFilter
  {
    public void Apply(Swagger.Operation operation, OperationFilterContext context)
    {
      var filterPipeline = context.ApiDescription.ActionDescriptor.FilterDescriptors;
      var isAuthorized = filterPipeline.Select(filterInfo => filterInfo.Filter).Any(filter => filter is AuthorizeFilter);
      var allowAnonymous = filterPipeline.Select(filterInfo => filterInfo.Filter).Any(filter => filter is IAllowAnonymousFilter);

      if (isAuthorized && !allowAnonymous)
      {
        if (operation.Parameters == null)
          operation.Parameters = new List<IParameter>();

        operation.Parameters.Add(new NonBodyParameter
        {
          Name = "Authorization",
          In = "header",
          Description = "access token",
          Required = true,
          Type = "string"
        });
      }
    }

    public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
    {
      IList<IDictionary<string, IEnumerable<string>>> security = swaggerDoc.SecurityDefinitions.Select(securityDefinition => new Dictionary<string, IEnumerable<string>>
        {
            {securityDefinition.Key, new string[] {"yourapi"}}
        }).Cast<IDictionary<string, IEnumerable<string>>>().ToList();


      swaggerDoc.Security = security;
    }
  }
}
